package com.second.app.thread.tongxin;

import java.time.LocalDateTime;

/**
 * @Author GYZ
 * <pre>
 *
 * </pre>
 */
public class TongXinDemo {


    public static void main(String[] args) {
        Target target = new Target();
        target.setChangeParam("a");
        Thread a = new Thread(target, "线程A");
        a.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        target.setChangeParam("b");
        Thread b = new Thread(target, "线程B");
        b.start();

    }


}

class Target implements Runnable {

    public static Object lock = new Object();

    public String changeParam;

    public void setChangeParam(String changeParam) {
        this.changeParam = changeParam;
    }


    @Override
    public void run() {
        if (changeParam.equalsIgnoreCase("a")) {
            doA();
        } else if (changeParam.equalsIgnoreCase("b")) {
            doB();
        }

    }

    private void doA() {

        synchronized (lock) {
            System.out.println(Thread.currentThread().getName() + "进入代码块时间：" + LocalDateTime.now());
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "离开代码块时间：" + LocalDateTime.now());
        }
    }

    private void doB() {
        synchronized (lock) {
            System.out.println(Thread.currentThread().getName() + "进入代码块时间："+LocalDateTime.now());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.notify();
            System.out.println(Thread.currentThread().getName() + "离开代码块时间："+LocalDateTime.now());
        }

    }
}
